package org.example.zuoye.service.impl;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.example.zuoye.entity.Admin;
import org.example.zuoye.entity.Doctor;
import org.example.zuoye.entity.Result;
import org.example.zuoye.mapper.DoctorMapper;
import org.example.zuoye.service.DoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author xinchen
 * @Date: 2024/08/11/ 20:36
 * @Description
 */
@Service
@Slf4j
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;
    /**
     * 分页查询
     */
    @Override
    public PageInfo search(Integer page, Integer limit, Doctor doctor) {
        try(Page<?> __ = PageHelper.startPage(page, limit)) {
            return new PageInfo<>(doctorMapper.search(doctor));
        }
    }

    /**
     * 批量删除
     */
    @Override
    public int remove(Integer[] ids) {
        return doctorMapper.deleteByIds(ids);
    }

    /**
     *  新增操作
     */
    @Override
    public int add(Doctor doctor) throws Exception {
      Doctor sdoctor = doctorMapper.selectByPhone(doctor.getPhone());
      if (!ObjectUtils.isEmpty(sdoctor)) {
          throw new Exception("该医生已存在");
      }
      return doctorMapper.insert(doctor);
    }

    /**
     * 修改操作
     */
    @Override
    public int update(Doctor doctor) throws Exception  {

        if(StringUtils.hasText(doctor.getPhone())){
            Doctor sdoctor = doctorMapper.selectByPhone(doctor.getPhone());
            System.out.println(sdoctor.getDocId());
            System.out.println(doctor.getDocId());
            if (!ObjectUtils.isEmpty(sdoctor) && !sdoctor.getDocId().equals(doctor.getDocId())) {
                throw new Exception("该手机号已存在");
            }
        }
        return doctorMapper.updateByPrimaryKey(doctor);
    }

    @Override
    public void export(HttpServletResponse response) {
        try {
            List<Doctor> infos = doctorMapper.findAll();
            // PageInfo search = this.search(1, 1000, null);
            // List<Doctor> infos = search.getList();

            if (CollectionUtils.isEmpty(infos)) {
                //响应提示信息
                Result r = Result.error("暂无数据");
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write(new ObjectMapper().writeValueAsString(r));
                return;
            }
            //设置响应excel文件格式类型
            response.setContentType("application/vnd.ms-excel");
            //2.设置响应数据的编码格式
            response.setCharacterEncoding("utf-8");
            //3.设置默认的文件名称
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("doctorRt", "UTF-8");
            //设置默认文件名称：兼容一些特殊浏览器
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //4.响应excel流
            EasyExcel
                    .write(response.getOutputStream(),Doctor.class)
                    .sheet("医生信息")
                    .doWrite(infos);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("当前导出数据异常，异常信息：{}",e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
